package com.zmn.oms.admin.controller.work.modify;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.zmn.base.engineer.common.enums.EngineerStopDistributeStatusEnum;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.admin.controller.work.WorkBaseController;
import com.zmn.oms.business.interfaces.master.OrderMasterBService;
import com.zmn.oms.business.interfaces.orderstock.OrderStockBService;
import com.zmn.oms.common.annotation.PageRequestCas;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.model.dto.master.MasterSharingDTO;
import com.zmn.oms.model.dto.master.MultiMasterDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.work.EngineerSharingVO;
import com.zmn.oms.model.vo.work.OperatePermissionVO;
import com.zmn.oms.model.vo.work.ZsOrderDistributeVO;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsCustomWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：多工程师
 *
 * @author liuying
 * @date 2018/12/10 17:45
 */
@Controller
@RequestMapping("/work/modify")
public class WorkMultiMasterController extends WorkBaseController {

    @Autowired
    private OrderMasterService orderMasterService;
    @Autowired
    private OrderMasterBService orderMasterBService;
    @Autowired
    private ZsCustomWorkBService zsCustomWorkBService;
    @Autowired
    private ZsDistributeWorkBService zsDistributeWorkBService;
    @Autowired
    ZsOrderWorkOperatePermissionBService orderWorkOperatePermissionBService;
    @Autowired
    private WorkFlowContextBService workFlowContextBService;
    @Autowired
    private OrderStockBService orderStockBService;
    @Autowired
    private OrderProductService orderProductService;

    /**
     * 多工程师
     */
    @RequestMapping(value = "/multimaster")
    @PageRequestCas(type = OrderConsts.ORDER_OP_TYPE_MULTI_MASTER)
    public ModelAndView multiMaster(Long orderId, Long workId) {
        ModelAndView mv = new ModelAndView("work/modify/multimaster");

        // 查询工程师列表
        List<OrderMaster> orderMasterList = orderMasterService.listMasterByWorkId(orderId, workId);
        // 从工程师
        List<OrderMaster> multiMasterList = Lists.newArrayList();
        Set<Integer> masterSet = Sets.newHashSet();
        OrderMaster orderMaster = null;

        for (OrderMaster master : orderMasterList) {
            if (Objects.equals(master.getType(), OrderConsts.ORDER_MASTER_TYPE_MAIN)) {
                // 主工程师
                orderMaster = master;
            } else {
                // 从工程师
                multiMasterList.add(master);
            }

            masterSet.add(master.getMasterId());
        }

        // 订单ID
        mv.addObject("orderId", orderId);
        mv.addObject("workId", workId);
        // 主工程师
        mv.addObject("orderMaster", orderMaster);
        // 从工程师
        mv.addObject("multiMasterList", multiMasterList);

        // 查询可派单工程师
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

        // 查询基础工程师列表(师傅状态(包含停单中和请假中),不判断在线状态，服务范围)
        List<ZsOrderDistributeVO> distributeMasterList = zsDistributeWorkBService.listBaseDistributeMaster(orderWork, orderDetail);
        List<KVDict> masterList = Lists.newArrayList();

        // 过滤库存量
        // this.filterMasterStock(orderWork, distributeMasterList);

        for (ZsOrderDistributeVO zsOrderDistributeVO : distributeMasterList) {
            String masterName = zsOrderDistributeVO.getMasterName();

            // 请假，停单拼上状态显示
            if (Objects.equals(EngineerStopDistributeStatusEnum.STOP_DISTRIBUTE.getCode(), zsOrderDistributeVO.getEngineerStatus())) {
                masterName += "(" + zsOrderDistributeVO.getEngineerStatusName() + ")";
            }

            KVDict kvDict = KVDict.builder().value(zsOrderDistributeVO.getMasterId()).text(String.format("%s-%s", masterName, zsOrderDistributeVO.getMasterPhone())).build();

            // 已选的工程师设置禁用
            if (masterSet.contains(zsOrderDistributeVO.getMasterId())) {
                kvDict.setDisabled(true);
            }

            masterList.add(kvDict);
        }

        mv.addObject("masterList", masterList);

        return mv;
    }


    /**
     * 保存多工程师
     *
     * @param multiMasterDTO 从工程师列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save/multimaster")
    public ResultDTO saveMultiMaster(@RequestBody @Valid MultiMasterDTO multiMasterDTO) {

        OperatePermissionVO operatePermission = orderWorkOperatePermissionBService.getOperatePermission(multiMasterDTO.getOrderId(), multiMasterDTO.getWorkId(), OrderConsts.ORDER_OP_TYPE_MULTI_MASTER);
        if (!operatePermission.getCanOperate()) {
            return ResultDTO.fail(operatePermission.getMsg());
        }

        try {
            zsCustomWorkBService.saveMultiMaster(multiMasterDTO);
            return ResultDTO.success();
        } catch (OmsBaseException e) {
            e.printStackTrace();
            return ResultDTO.fail(e.getMessage());
        }
    }


    /**
     * 多工程师分润
     */
    @RequestMapping(value = "/mastersharing")
    public ModelAndView masterSharing(Long orderId, Long workId) {
        ModelAndView mv = new ModelAndView("work/modify/mastersharing");
        mv.addObject("orderId", orderId);
        mv.addObject("workId", workId);

        // 查询工程师列表
        List<OrderMaster> orderMasterList = orderMasterService.listMasterByWorkId(orderId, workId);

        Map<Integer, String> identityMap = orderMasterBService.listMasterIdentityMap(orderMasterList.stream().map(OrderMaster::getMasterId).collect(Collectors.toList()));

        List<EngineerSharingVO> engineerList = Lists.newArrayListWithCapacity(orderMasterList.size());

        orderMasterList.forEach(item -> {
            EngineerSharingVO engineerSharingVO = BeanMapper.map(item, EngineerSharingVO.class);
            // 设置工程师身份
            if (Objects.nonNull(identityMap) && identityMap.containsKey(item.getMasterId())) {
                engineerSharingVO.setIdentityName(Optional.ofNullable(identityMap.get(item.getMasterId())).orElse("工程师"));
            }
            engineerList.add(engineerSharingVO);
        });

        mv.addObject("masterList", engineerList);

        return mv;
    }


    /**
     * 多工程师分润保存
     */
    @RequestMapping(value = "/save/mastersharing")
    @ResponseBody
    public ResultDTO saveMasterSharing(@RequestBody @Valid MasterSharingDTO masterSharingDTO) {

        try {
            orderMasterBService.updateOrderMasterShare(masterSharingDTO);
            workFlowContextBService.autoFlow(masterSharingDTO.getOrderId(), masterSharingDTO.getWorkId());
        } catch (OmsBaseException e) {
            return ResultDTO.fail(e.getMessage());
        }

        return ResultDTO.success();
    }

    /*
    private void filterMasterStock(OrderWork orderWork, List<ZsOrderDistributeVO> distributeMasterList) {
        List<Integer> masterIdList = distributeMasterList.stream()
                .map(ZsOrderDistributeVO::getMasterId)
                .collect(Collectors.toList());

        DistributeMasterStockBO distributeMasterStockBO = DistributeMasterStockBO.builder()
                .engineerIdList(masterIdList)
                .dutyTime(orderWork.getDutyTime())
                .orderId(orderWork.getOrderId())
                .workId(orderWork.getWorkId())
                .build();
        Map<Integer, Boolean> masterStockMap = orderStockBService.canDistributeMaster(distributeMasterStockBO);
        distributeMasterList.removeIf(zsOrderDistributeVO -> !masterStockMap.get(zsOrderDistributeVO.getMasterId()));
    }
    */

}
